package acs.bridge;

import acs.bridge.model.bm_file_model;
import com.jcraft.jsch.*;
import com.jcraft.jsch.Logger;
import org.apache.log4j.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * acs.bridge
 * User: KuznetsovStV
 * Date: 23.06.13
 * Time: 19:46
 */
public class bm_load_file_sftp implements bm_load_file_interface {
    org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(this.getClass().getName());

    private String username;
    private String host;
    private String port;
    private String password;
    private String srcPath;
    private String pattern;


    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getHost() {
        return host;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getPort() {
        return port;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return password;
    }

    @Override
    public void get_file(String a_file_name, String a_dst_path) throws BridgeException {
        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp sftpChannel = null;
        logger.info("get_file start");
        try {
            session = jsch.getSession(username, host, Integer.valueOf(port));
            logger.info("SFTP getSession");
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.setTimeout(60000); // timeout  1 min
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;
            logger.info("SFTP session connected for copy");

            sftpChannel.get(srcPath + a_file_name, a_dst_path);
            logger.info("SFTP get");
        } catch (JSchException e) {
            logger.error(e.getMessage() + " (JSchException)");
            logger.error(e.getStackTrace());
            throw new BridgeException(e.getMessage());
        } catch (SftpException e) {
            logger.error(e.getMessage() + " (SftpException)");
            logger.error(e.getStackTrace());
            throw new BridgeException(e.getMessage());
        } finally {
            logger.info("SFTP finally");
            if (sftpChannel != null)
                sftpChannel.exit();
            if (session != null)
                session.disconnect();
            logger.info("SFTP disconnected");
        }
    }

    @Override
    public List<bm_file_model> get_directory_list() {

        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp sftpChannel = null;
        List<bm_file_model> l_dir_list = new ArrayList<bm_file_model>();
        try {
            logger.info("Start sftload precessing {host=" + host + ",username=" + username + "}");
            session = jsch.getSession(username, host, new Integer(port));
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.setTimeout(60000); // timeout  1 min
            session.connect();
            logger.info("SFTP session connected");
            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;


            Enumeration vEnum = sftpChannel.ls(getSrcPath() + pattern).elements();

            SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmssZ");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT-00:00"));
            SimpleDateFormat sd_z_date = new SimpleDateFormat("ddMMyyyy_HHmmss");
            sd_z_date.setTimeZone(TimeZone.getTimeZone("GMT-00:00"));

            if (vEnum != null)
                while (vEnum.hasMoreElements()) {
                    ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) vEnum.nextElement();
                    String fr_id = lsEntry.getFilename() + "_" + sdf.format(new Date(lsEntry.getAttrs().getMTime() * 1000L)) + "_" + lsEntry.getAttrs().getSize();
                    bm_file_model l_bm_file_model = new bm_file_model();
                    l_bm_file_model.setFr_id(fr_id);
                    l_bm_file_model.setFile_name(lsEntry.getFilename());
                    l_bm_file_model.setFile_path(getSrcPath());
                    l_bm_file_model.setLast_modified(sd_z_date.format(new Date(lsEntry.getAttrs().getMTime() * 1000L)));
                    l_bm_file_model.setFile_size(new BigDecimal(lsEntry.getAttrs().getSize()));
                    l_dir_list.add(l_bm_file_model);


                }
        } catch (JSchException e) {
            logger.error(e.getMessage());
        } catch (SftpException e) {
            logger.error(e.getMessage());
        } finally {
            if (sftpChannel != null)
                sftpChannel.exit();
            if (session != null)
                session.disconnect();
        }

        return l_dir_list;
    }

    public void setSrcPath(String srcPath) {
        this.srcPath = srcPath;
    }

    public String getSrcPath() {
        return srcPath;
    }


    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public String getPattern() {
        return pattern;
    }
}
